package com.jarveis.frame.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 操作系统工具类
 * 
 * @author liuguojun
 */
public final class OSUtil {

	/**
	 * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux等.
	 * 
	 * @return String
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}

	/**
	 * 获取本机ip地址
	 * 
	 * @return String
	 * @throws UnknownHostException
	 */
	public static String getLocalIp() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostAddress();
	}

	/**
	 * 获取本机MAC地址
	 * 
	 * @return String
	 * @throws IOException
	 */
	public static String getLocalMac() throws IOException {
		String mac;
		
		String os = getOSName();
		if (os.startsWith("windows")) {
			// 本地是windows
			mac = getWindowsMAC();
		} else {
			// 本地是非windows系统 一般就是unix
			mac = getUnixMAC();
		}
		
		return mac;
	}

	/**
	 * 获取unix网卡的mac地址.
	 * 
	 * @return mac地址
	 * @throws IOException
	 */
	private static String getUnixMAC() throws IOException {
		String mac = null;
		// linux下的命令，一般取eth0作为本地主网卡
		Process process = Runtime.getRuntime().exec("ifconfig eth0");
		// 显示信息中包含有mac地址信息
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(process.getInputStream()));
		String line = null;
		int index = -1;
		while ((line = bufferedReader.readLine()) != null) {
			// 寻找标示字符串[hwaddr]
			index = line.toLowerCase().indexOf("hwaddr");
			if (index >= 0) {
				// 取出mac地址并去除2边空格
				mac = line.substring(index + "hwaddr".length() + 1).trim();
				break;
			}
		}

		return mac;
	}

	/**
	 * 获取widnows网卡的mac地址.
	 * 
	 * @return mac地址
	 * @throws IOException
	 */
	private static String getWindowsMAC() throws IOException {
		String mac = null;
		// windows下的命令，显示信息中包含有mac地址信息
		Process process = Runtime.getRuntime().exec("ipconfig /all");
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(process.getInputStream()));
		String line = null;
		int index = -1;
		while ((line = bufferedReader.readLine()) != null) {
			// 寻找标示字符串[physical address]
			index = line.toLowerCase().indexOf("physical address");
			if (index >= 0) {
				// 寻找":"的位置
				index = line.indexOf(":");
				if (index >= 0) {
					// 取出mac地址并去除2边空格
					mac = line.substring(index + 1).trim();
				}
				break;
			}
		}

		return mac;
	}
}
